import json
import matplotlib.pyplot as plt
import numpy as np

from matplotlib.pyplot import MultipleLocator

result={}
def analyze(data_path):
    # 分析log日志，记录相关信息，存储在log_dic中
    # log_dic格式如下：'6922': {'cpu': '10', 'ProcessA': {'start': '146767', 'end': '146781'}, 
    # 'ProcessB': {'start': '146949', 'end': '146974'}}
    log_dic={}
    with open(data_path, 'r') as f:
        cout = 0
        process_times = {}
        for line in f:
            line=line.strip()
            # print(line)
            if 'static_multistream' in line:
                # line = line.split(']')[1]
                # print(line)
                frame_id=line.split('|')[1]
                frame_id=frame_id.split(':')[1]
                cpu_id=line.split('|')[3].split(':')[1]
                process=line.split('|')[4]
                A_B=process.split(':')[0]
                sta_end=process.split(':')[1]
                ti=process.split(':')[2]
                if frame_id not in log_dic:
                    log_dic[frame_id]={}
                    if A_B not in log_dic[frame_id]:
                        log_dic[frame_id][A_B]={}
                        if sta_end not in log_dic[frame_id][A_B]:
                            log_dic[frame_id][A_B][sta_end]=ti
                else:
                    
                    if A_B not in log_dic[frame_id]:
                        log_dic[frame_id][A_B]={}
                        log_dic[frame_id][A_B][sta_end]=ti
                    else:
                            log_dic[frame_id][A_B][sta_end]=ti
    # print(log_dic)
    
        
    return log_dic              
                        
                    
                
        # print(log_dic)
def calculate_times(log_dic):
    countA=0
    countB=0
    totalA=0
    totalB=0
    
    total_frame=0# 系统帧数
    total_time=0# 系统总耗时
    process_a_times = []
    process_b_times = []
    over_start_time=int(log_dic[list(log_dic.keys())[0]]['ProcessA']['start'])
    over_end_time=int(log_dic[list(log_dic.keys())[0]]['ProcessA']['end'])
    for frame_id,inner_item in log_dic.items():
        total_frame+=1
        startt=[]
        endt=[]
        for key,value in inner_item.items():
            start=int(value['start'])
            end=int(value['end'])
            if start<over_start_time:
                over_start_time=start
            if end>over_end_time:
                over_end_time=end
            startt.append(start)
            endt.append(end)
            time=end-start
            if key=='ProcessA':
                countA+=1
                totalA+=time
                process_a_times.append(time)
                
            elif key=='ProcessB':
                countB+=1
                totalB+=time
                process_b_times.append(time)
                
        total_time+=(max(endt)-min(startt))/1000
        
    result['ave_processA']=totalA/countA
    result['ave_processB']=totalB/countB
    process_a_times.sort()
    process_b_times.sort()
    process_a_p99 = process_a_times[int(len(process_a_times) * 0.99)]
    process_b_p99 = process_b_times[int(len(process_b_times) * 0.99)]
    result['p99_processA']=process_a_p99
    result['p99_processB']=process_b_p99
    process_a_p90 = process_a_times[int(len(process_a_times) * 0.90)]
    process_b_p90 = process_b_times[int(len(process_b_times) * 0.90)]
    result['p90_processA']=process_a_p90
    result['p90_processB']=process_b_p90
    result['Average throughput']=total_frame/((over_end_time-over_start_time)/1000)
    result['Average Frame Rate']=total_frame/total_time
    print(result)
    with open('./result.json','w')as wr:
        json.dump(result,wr)

       
def plot_figuer(log_dic):
    process_names = list(log_dic.keys())
    process_a_starts = []
    process_a_ends = []
    process_b_starts = []
    process_b_ends = []
    min_id=int(list(log_dic.keys())[0])
    max_id=int(list(log_dic.keys())[0])
    for frame_id,inner_item in log_dic.items():
        if int(frame_id)<min_id:
            min_id=int(frame_id)
        if int(frame_id)>max_id:
            max_id=int(frame_id)
        
        for key,value in inner_item.items():
            if key=='ProcessA':
                process_a_starts.append((int(value['start'])/10))
                process_a_ends.append((int(value['end'])/10))
            elif key=='ProcessB':
                process_b_starts.append((int(value['start'])/10))
                process_b_ends.append((int(value['end'])/10))
    
    startime=min(int(min(process_a_starts)), int(min(process_b_starts)))
    print('st',startime)
    plt.figure(figsize=(24, 12))# 绘制ProcessA的时间段

    for i in range(len(process_a_starts)):
        if process_a_starts[i] is not None:
            s=(process_a_starts[i])-startime
            e=(process_a_ends[i])-startime
            plt.plot([s, e], [int(process_names[i]), int(process_names[i])], 'b',linewidth=2)
            # print(process_names[i])
        
    # 绘制ProcessB的时间段
    j=0
    for i in range(len(process_b_starts)):
        if process_b_starts[i] is not None:
            s=(process_b_starts[i]-startime)
            e=(process_b_ends[i]-startime)
            plt.plot([s, e], [int(process_names[i]), int(process_names[i])], 'r', linewidth=2)
    
    # 设置图形属性
    ylabel_len=int((max_id-min_id)/40)+1
    yl=[]
    for i in range(ylabel_len):
        # print(min_id+i*10)
        yl.append(min_id+i*40)
    plt.yticks(range(min_id,max_id,40),range(min_id,max_id,40))
    plt.xticks(range(0, (max(int(max(process_a_ends)), int(max(process_b_ends))) -startime),250))
    plt.ylim(min_id, max_id)
    plt.xlim(0, (max(int(max(process_a_ends)), int(max(process_b_ends))) -startime))
    plt.xlabel('Time')
    plt.ylabel('frame ID')
    plt.title('ProcessA and ProcessB Scheduling Timeline')
    plt.grid(True)
    plt.axhline(y=0, color='black', linewidth=0.5)  # 水平参考线
    plt.axvline(x=0, color='black', linewidth=0.5)
    
    plt.tight_layout()
    plt.savefig('./time2.png')




                
            



if __name__ == '__main__':
    data_path='/home/ubt-346/devdata1/tpp/xm/trace_analysis.log'
    logdic=analyze(data_path)
    # calculate_times(logdic)
    plot_figuer(logdic)